package gov.pbc.gx.nn.pz.bdf.view;

import gov.pbc.gx.nn.pz.bdf.entity.Dept;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.bstek.bdf2.core.CoreHibernateDao;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.dorado.annotation.Expose;

@Component("deptInit")
public class DeptInit extends CoreHibernateDao {

	@Expose
	public <T> void init() throws Exception {

		// 创建saxReader对象
		SAXReader reader = new SAXReader();
		// 通过read方法读取一个文件 转换成Document对象
		Document document = reader.read(new File(DeptInit.class.getResource(
				"dept.xml").toURI()));
		// 获取根节点元素对象
		Element node = document.getRootElement();

		final List<Element> list1 = new ArrayList<Element>();
		list1.addAll(node.elements());

		this.doInHibernateSession(new ISessionCallback<Void>() {

			@Override
			public Void doInSession(Session session) {
				for (int i = 0; i < list1.size(); i++) {
					Dept dept = new Dept();

					dept.setId(list1.get(i).element("ou").getText());
					dept.setName(list1.get(i).element("name").getText());
					String parentId = list1.get(i)
							.element("PBCSupervisorydepartment").getText();
					dept.setParentId(StringUtils.isEmpty(parentId)?null:parentId);
					dept.setCode(list1.get(i).element("PBCOrgNumber").getText());
					dept.setType(Integer.parseInt(list1.get(i)
							.element("PBCOuType").getText()));
					dept.setCompanyId(ContextHolder.getLoginUser().getCompanyId());
					session.save(dept);
				}
				return null;
			}
		});

	}

}
